package com.uw.uwrpc.core.consumer;

import com.uw.uwrpc.core.meta.InstanceMeta;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class InstanceHolder {

    @Getter
    private final List<InstanceMeta> activeInstances = new ArrayList<>();
    private final List<InstanceMeta> isolateInstances = new ArrayList<>();
    @Getter
    private final List<InstanceMeta> halfOpenInstances = new ArrayList<>();
    
    
    public InstanceHolder() {
    }

    public synchronized void updateAllActiveInstance(List<InstanceMeta> activeInstances) {
        log.debug(" ==> active instance = {}", activeInstances);
        this.activeInstances.clear();
        log.debug(" ==> active instance clear");
        this.activeInstances.addAll(activeInstances);
        log.debug(" ==> active instance add all");
    }

    public synchronized void isolateInstance(InstanceMeta instanceMeta) {
        log.debug(" ==> isolate instance = {}", instanceMeta);
        activeInstances.remove(instanceMeta);
        log.debug(" ==> active instance = {}", activeInstances);
        isolateInstances.add(instanceMeta);
        log.debug(" ==> isolate instance = {}", isolateInstances);
    }

    public synchronized void halfOpenInstance() {
        log.debug(" ====> half open isolate instance: " + isolateInstances);
        halfOpenInstances.clear();
        log.debug(" ====> half open instance clear");
        halfOpenInstances.addAll(isolateInstances);
        log.debug(" ====> half open add all isolate instance" );
    }


    public synchronized InstanceMeta getHalfOpenInstance() {
        if (halfOpenInstances.isEmpty()) {
            return null;
        }

        return halfOpenInstances.remove(0);
    }

}
